﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Cookies["Login"] != null)
            {
                txtUsername.Text = Request.Cookies["Login"]["Username"];
                txtPassword.Text = Request.Cookies["Login"]["Password"];
            }
            else if (Session["Register"] != null)
            {
                CustomValidator1.ErrorMessage = Session["Register"].ToString();
                CustomValidator1.IsValid = false;
                Session.Remove("Register");
            }
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text;
        string password = txtPassword.Text;
        int diaryID;
        bool isLogin = CheckLogin(username, password, out diaryID);
        if (isLogin)
        {
            Session.Add("DiaryID", diaryID);
            Session.Add("Username", username);
            if (cbRemember.Checked)
            {
                HttpCookie ck = new HttpCookie("Login");
                ck.Values["Username"] = username;
                ck.Values["Password"] = password;
                ck.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(ck);
            }
            Response.Redirect("Default.aspx");
        }
        else
        {
            CustomValidator1.IsValid = false;
            CustomValidator1.ErrorMessage = "Login Fail";
        }
    }

    private bool CheckLogin(string username, string password, out int diaryID)
    {
        diaryID = -1;
        using (var db = new DiaryOnlineDataContext())
        {
            Diary d = db.Diaries.FirstOrDefault(x => x.Username == username && x.Password == password);
            if (d != null)
            { 
                diaryID = d.DiaryID;
                return true;
            }
            return false;
        }
    }
}
